package com.zhny.project.exec.outcome.controller;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhny.framework.config.RuoYiConfig;
import com.zhny.project.count.algorithm.service.IAlgorithmService;
import com.zhny.project.count.ification.domain.Ification;
import com.zhny.project.count.ification.service.IIficationService;
import com.zhny.project.exec.algorithm.domain.ExecAlgorithm;
import com.zhny.project.shell.IShellService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhny.framework.aspectj.lang.annotation.Log;
import com.zhny.framework.aspectj.lang.enums.BusinessType;
import com.zhny.project.exec.outcome.service.IOutcomeService;
import com.zhny.framework.web.controller.BaseController;
import com.zhny.framework.web.domain.AjaxResult;
import com.zhny.common.utils.poi.ExcelUtil;
import com.zhny.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 算法执行结果Controller
 *
 * @author lxh
 * @date 2019-10-17
 */
@Controller
@RequestMapping("/exec/outcome")
public class OutcomeController extends BaseController
{
    private String prefix = "exec/outcome";

    @Autowired
    private IOutcomeService outcomeService;
    @Autowired
    private IIficationService ificationService;
    @Autowired
    private IShellService shellService;

    @RequiresPermissions("exec:outcome:view")
    @GetMapping()
    public String outcome(Model model)
    {
        List<Ification> ifications = ificationService.selectIficationPage(new Ification());
        model.addAttribute("ification",ifications);
        return prefix + "/outcome";
    }

    /**
     * 查询算法执行结果列表
     */
    @RequiresPermissions("exec:outcome:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExecAlgorithm execAlgorithm)
    {
        startPage();
        List<ExecAlgorithm> list = outcomeService.selectOutcomeList(execAlgorithm);
        return getDataTable(list);
    }

    /**
     * 导出算法执行结果列表
     */
    @RequiresPermissions("exec:outcome:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ExecAlgorithm execAlgorithm)
    {
        List<ExecAlgorithm> list = outcomeService.selectOutcomeList(execAlgorithm);
        ExcelUtil<ExecAlgorithm> util = new ExcelUtil<ExecAlgorithm>(ExecAlgorithm.class);
        return util.exportExcel(list, "outcome");
    }

    /**
     * 新增算法执行结果
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存算法执行结果
     */
    @RequiresPermissions("exec:outcome:add")
    @Log(title = "算法执行结果", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ExecAlgorithm execAlgorithm)
    {
        return toAjax(outcomeService.insertOutcome(execAlgorithm));
    }

    /**
     * 修改算法执行结果
     */
    @GetMapping("/modify/{exceKey}")
    public String edit(@PathVariable("exceKey") String exceKey, ModelMap mmap)
    {
        ExecAlgorithm execAlgorithm = outcomeService.selectOutcomeById(exceKey);
        shellService.downResultFile(shellService.getShellPath(),execAlgorithm.getAlgorithmFile(),
                RuoYiConfig.getResultPath()+"/result.txt");

        if("A01".equals(execAlgorithm.getAlgorithmId()) ){
            mmap.put("resultFile", "/result.txt");
            return prefix + "/editpcautil";
//            editpcautil
        }else if ("A02".equals(execAlgorithm.getAlgorithmId())){
            mmap.put("resultFile", "/pearson.txt");
            return prefix + "/editPearson";
        }else{
            return prefix + "/editSpearman";
        }
    }

    @GetMapping("/judge/{exceKey}")
    @ResponseBody
    public Map<String, Object>  judge(@PathVariable("exceKey") String exceKey)
    {
        ExecAlgorithm execAlgorithm = outcomeService.selectOutcomeById(exceKey);
        Map<String, Object> map = new HashMap<String, Object>();
        int mun = 0;

        if("A01".equals(execAlgorithm.getAlgorithmId()) ) {
            mun = 1;
            map.put("flag", mun);
            return map;
//            editpcautil
        } else if ("A02".equals(execAlgorithm.getAlgorithmId())) {
            mun = 2;
            map.put("flag", mun);
            return map;
        } else {
            mun = 3;
            map.put("flag", mun);
            return map;
        }
    }

    /**
     * 修改保存算法执行结果
     */
    @RequiresPermissions("exec:outcome:edit")
    @Log(title = "算法执行结果", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ExecAlgorithm execAlgorithm)
    {
        return toAjax(outcomeService.updateOutcome(execAlgorithm));
    }

    /**
     * 删除算法执行结果
     */
    @RequiresPermissions("exec:outcome:remove")
    @Log(title = "算法执行结果", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(outcomeService.deleteOutcomeByIds(ids));
    }

    //@RequiresPermissions("exec:outcome:view")
    @GetMapping("/download/{exceKey}")
    public void downLoadResult(@PathVariable("exceKey") String exceKey, HttpServletRequest request,
                               HttpServletResponse response)
    {
        ExecAlgorithm execAlgorithm = outcomeService.selectOutcomeById(exceKey);
        shellService.downResultFile(shellService.getShellPath(),execAlgorithm.getAlgorithmFile(),
                RuoYiConfig.getResultPath()+"/result.txt");
        try {
            File file = new File(RuoYiConfig.getResultPath()+"/result.txt");
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            response.setHeader("Content-Length", String.valueOf(file.length()));

            int length = 0;
            byte[] buffer = new byte[1024];

            FileInputStream fis = new FileInputStream(file);
            OutputStream os = response.getOutputStream();

            while (-1 != (length = fis.read(buffer, 0, buffer.length))) {
                os.write(buffer, 0, length);
            }

            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
